﻿using System;
using System.Drawing;
using System.Threading.Tasks;

namespace GTAFingerprinterCore.Pictures
{
    public static class CaptureTool
    {
        public static async Task<Image> CaptureWindow(string title)
        {
            var hWnd = WIN32_API.FindWindow(null, title);
            if (hWnd == IntPtr.Zero)
            {
                throw new InvalidOperationException("指定截图的窗口不存在");
            }
            return await CaptureWindow(hWnd);
        }

        public static async Task<Image> CaptureScreen()
        {
            return await CaptureWindow(WIN32_API.GetDesktopWindow());
        }

        public static async Task<Image> CaptureWindow(IntPtr hWnd)
        {
            var hDC = WIN32_API.GetDC(hWnd);
            var hMemDC = WIN32_API.CreateCompatibleDC(hDC);
            WIN32_API.RECT rECT;
            WIN32_API.GetClientRect(hWnd, out rECT);
            WIN32_API.SIZE size;
            size.cx = rECT.right - rECT.left;
            size.cy = rECT.bottom - rECT.top;

            var m_HBitmap = WIN32_API.CreateCompatibleBitmap(hDC, size.cx, size.cy);
            if (m_HBitmap != IntPtr.Zero)
            {
                var hOld = WIN32_API.SelectObject(hMemDC, m_HBitmap);
                await Task.Run(() =>
                {
                    WIN32_API.BitBlt(hMemDC, 0, 0, size.cx, size.cy, hDC, 0, 0, WIN32_API.SRCCOPY | WIN32_API.CAPTUREBLT);
                });
                WIN32_API.SelectObject(hMemDC, hOld);
                WIN32_API.DeleteDC(hMemDC);
                WIN32_API.ReleaseDC(hWnd, hDC);
                var img = Image.FromHbitmap(m_HBitmap);
                WIN32_API.DeleteObject(m_HBitmap);
                return img;
            }
            return null;
        }
    }
}